package com.zhaodui.restapi.base;

import com.baidu.aip.ocr.AipOcr;
import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.HybridBinarizer;
import com.zhaodui.jdwx.jdwxController;
import com.zhaodui.order.entity.FxjOrderAttaEntity;
import com.zhaodui.order.page.FxjOrderMainPage;
import com.zhaodui.pa.entity.FxjPaInsureEntity;
import com.zhaodui.pos.entity.PosXjfjEntity;
import com.zhaodui.pro.entity.FxjProMainEntity;
import com.zhaodui.restapi.entity.FileMeta;
import com.zhaodui.restapi.entity.FkInputEntity;
import com.zhaodui.restapi.entity.fxjMenuEntity;
import com.zhaodui.sys.entity.FxjFileListEntity;
import com.zhaodui.sys.entity.FxjOtherLoginEntity;
import com.zhaodui.util.Base64Utils;
import com.zhaodui.util.QRcodeUtil;
import com.zhaodui.util.alioss.AliyunOSSClientUtil;
import com.zhaodui.util.fxjUtil;
import com.zhaodui.util.printUtil;
import com.zhaodui.util.word.Java2word;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.jeecgframework.core.util.DateUtils;
import org.jeecgframework.core.util.ResourceUtil;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.core.util.ZipUtil;
import org.jeecgframework.jwt.util.ResponseMessage;
import org.jeecgframework.web.system.pojo.base.*;
import org.jeecgframework.web.system.service.SystemService;
import org.jeecgframework.web.system.service.UserService;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Validator;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URL;
import java.net.URLEncoder;
import java.util.*;

import static com.xiaoleilu.hutool.date.DateTime.now;
import static com.zhaodui.util.FixImageExifUtil.getRotateAngleForPhoto;
import static com.zhaodui.util.FixImageExifUtil.rotateImage;

/**
 * TSUser的Restful API
 * 
 *  path/ POST    --> 新增 (CREATE)
 *  path/id  GET -->  查询 (READ)
 *  path/id  PUT  -->  更新 (UPDATE)
 *  path/id  DELETE --> 删除 (DELETE)
 * 
 * @author liuht
 */
//update--begin--author:zhangjiaqiang date:20171030 for:增加swagger支持
@Api(value="baseRest",description="用户菜单管理",tags="BaserestController")
//update--end--author:zhangjiaqiang date:20171030 for:增加swagger支持
@Controller
@RequestMapping(value = "/base")
public class BaseRestController {
    @Autowired
    UserService userService;
    @Autowired
    SystemService systemService;
	@Autowired
	private Validator validator;
	public static final String APP_ID = "15722255";
	public static final String API_KEY = "OwTicgbGnThboBRKV3OmwVsx";
	public static final String SECRET_KEY = "8qAgMPytAEFvo5CEAc4ywe1eVoGu2iyN";
	/**
	 * 访问地址：http://localhost:8080/jeecg/rest/user/name/{id}
	 * @return
	 */
	@RequestMapping(value = "/webroot", method = RequestMethod.GET)
	@ResponseBody
	//update--begin--author:zhangjiaqiang date:20171030 for:增加swagger支持
	@ApiOperation(value="获取webroot",notes="获取webroot",httpMethod="GET",produces="application/json")
	//update--end--author:zhangjiaqiang date:20171030 for:增加swagger支持
	public String getbyusername() {
		return ResourceUtil.getConfigByName("restroot");
	}
	@RequestMapping(value = "/getmenu/{username}", method = RequestMethod.GET)
	@ResponseBody
	@ApiOperation(value="根据username获取用户菜单",notes="根据username获取用户菜单",httpMethod="GET",produces="application/json")
	public ResponseMessage<?> getmenu(@ApiParam(required=true,name="username",value="username")@PathVariable("username") String username) {
		if(StringUtil.isEmpty(username)){
			username = "admin";
		}
		TSUser tsUser = systemService.findUniqueByProperty(TSUser.class,"userName",username);
		if(tsUser==null){
			return org.jeecgframework.jwt.util.Result.error("菜单获取失败");
		}
		Map<String, TSFunction> task = userService.getLoginUserFunctionapi(tsUser.getId());
		List<fxjMenuEntity> tasklist =  new ArrayList<fxjMenuEntity>();

		for(TSFunction t :task.values()){
			if(9==t.getFunctionType()&&0==t.getFunctionLevel()){
				fxjMenuEntity tt = new fxjMenuEntity();
				tt.setId(t.getId());
				tt.setOrderNum(t.getFunctionOrder());
				tt.setText(t.getFunctionName());
				tt.setParentId(t.getId());
				tt.setBadge("");
//				tt.setLink(t.getFunctionUrl());
				tt.setBadgeDot(false);
				tt.setGroup(false);
				tt.setI18n(t.getFunctionName());

				List<TSFunction> tsubfunc = t.getTSFunctions();
                Collections.sort(tsubfunc,new Comparator<TSFunction> (){
                    public int compare(TSFunction arg0, TSFunction arg1) {
                        return arg0.getFunctionOrder().compareTo(arg1.getFunctionOrder());
                    }
                });
				List<fxjMenuEntity.ChildrenBean> childre = new ArrayList<fxjMenuEntity.ChildrenBean>();
				for(TSFunction tsub:tsubfunc){
					fxjMenuEntity.ChildrenBean childrenBean = new fxjMenuEntity.ChildrenBean();
					childrenBean.setId(tsub.getId());
					childrenBean.setBadge("");
					childrenBean.setBadgeDot(false);
					childrenBean.setOrderNum(tsub.getFunctionOrder());
					childrenBean.setText(tsub.getFunctionName());
					childrenBean.setParentId(t.getId());
					childrenBean.setLink(tsub.getFunctionUrl());
					childrenBean.setI18n(tsub.getFunctionName());
					childrenBean.setGroup(false);
					childrenBean.setIcon(tsub.getFunctionIconStyle());

					List<TSFunction> tsubfunc1 = tsub.getTSFunctions();
                    Collections.sort(tsubfunc1,new Comparator<TSFunction> (){
                        public int compare(TSFunction arg0, TSFunction arg1) {
                            return arg0.getFunctionOrder().compareTo(arg1.getFunctionOrder());
                        }
                    });
					if(tsubfunc1!=null&&tsubfunc1.size()>0){
						childrenBean.setGroup(true);

					}
					List<fxjMenuEntity.ChildrenBean> childre1 = new ArrayList<fxjMenuEntity.ChildrenBean>();
					for(TSFunction tsub1:tsubfunc1) {
						fxjMenuEntity.ChildrenBean childrenBean1 = new fxjMenuEntity.ChildrenBean();
						childrenBean1.setId(tsub1.getId());
						childrenBean1.setBadge("");
						childrenBean1.setBadgeDot(true);
						childrenBean1.setOrderNum(tsub1.getFunctionOrder());
						childrenBean1.setText(tsub1.getFunctionName());
						childrenBean1.setParentId(tsub.getId());
						childrenBean1.setLink(tsub1.getFunctionUrl());
						childrenBean1.setI18n(tsub1.getFunctionName());
						childrenBean1.setGroup(false);
						childrenBean1.setIcon(tsub1.getFunctionIconStyle());
//						childrenBean1.setChildren(childre1);
						for(TSFunction tsubhas:task.values()){
							if(tsubhas.getId().equals(childrenBean1.getId())){
								childre1.add(childrenBean1);
							}
						}
					}

					childrenBean.setChildren(childre1);
					for(TSFunction tsubhas:task.values()){
						if(tsubhas.getId().equals(childrenBean.getId())){
							childre.add(childrenBean);
						}
					}
				}
				tt.setChildren(childre);
				for(TSFunction tsubhas:task.values()){
					if(tsubhas.getId().equals(tt.getId())){
						tasklist.add(tt);
					}
				}
			}
		}

		if (tasklist.size()<=0) {
			return org.jeecgframework.jwt.util.Result.error("获取用户菜单");
		}


		return org.jeecgframework.jwt.util.Result.success(tasklist);
	}


    @RequestMapping(value = "/getDictValue/{tyepgroup}", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value="根据tyepgroup获取字典信息",notes="根据tyepgroup获取字典信息",httpMethod="GET",produces="application/json")
    public ResponseMessage<?> getDict(@ApiParam(required=true,name="tyepgroup",value="tyepgroup")@PathVariable("tyepgroup") String tyepgroup) {
        List<TSType> task  = ResourceUtil.getCacheTypes(tyepgroup.toLowerCase());
        return org.jeecgframework.jwt.util.Result.success(task);
    }


	@RequestMapping(value = "/getDictentityValue/{entity}", method = RequestMethod.GET)
	@ResponseBody
	@ApiOperation(value="根据entity获取字典信息",notes="根据entity获取字典信息",httpMethod="GET",produces="application/json")
	public ResponseMessage<?> getDictentityValue(@ApiParam(required=true,name="entity",value="entity")@PathVariable("entity") String entity) {
		List<TSType> task  = new ArrayList<>();
		if("ins".equals(entity)){
			List<FxjPaInsureEntity> fxjPaInsureEntityList = systemService.findByQueryString(" from FxjPaInsureEntity");
            for(FxjPaInsureEntity T:fxjPaInsureEntityList){
				TSType  tsType = new TSType();
				tsType.setTypecode(T.getInsNo());
				tsType.setTypename(T.getInsName());
				task.add(tsType);
			}
		}
		return org.jeecgframework.jwt.util.Result.success(task);
	}

	@RequestMapping(value = "/getsysuser/{syscode}", method = RequestMethod.GET)
	@ResponseBody
	@ApiOperation(value="根据syscode获取用户信息",notes="根据syscode获取用户信息",httpMethod="GET",produces="application/json")
	public ResponseMessage<?> getsysuser(@ApiParam(required=true,name="syscode",value="syscode")@PathVariable("syscode") String syscode) {
		List<TSType> task  = new ArrayList<>();

			List<TSUser> TSUserList = systemService.findByQueryString(" from TSUser where userType = 1 and deleteFlag = 0 ");
			for(TSUser T:TSUserList){
				TSType  tsType = new TSType();
				tsType.setTypecode(T.getUserName());
				tsType.setTypename(T.getRealName());
				task.add(tsType);
			}

		return org.jeecgframework.jwt.util.Result.success(task);
	}







	@RequestMapping(value = "/getuser/{username}", method = RequestMethod.GET)
	@ResponseBody
	@ApiOperation(value="根据username获取用户信息",notes="根据username获取用户信息",httpMethod="GET",produces="application/json")
	public ResponseMessage<?> getuser(@ApiParam(required=true,name="username",value="username")@PathVariable("username") String username) {
		TSUser task = systemService.findUniqueByProperty(TSUser.class,"userName",username);
		if (task == null) {
			FxjOtherLoginEntity fxjOtherLoginEntity = userService.findUniqueByProperty(FxjOtherLoginEntity.class, "otherid", username);
			if (fxjOtherLoginEntity != null) {
				task = systemService.findUniqueByProperty(TSUser.class,"userName",fxjOtherLoginEntity.getUsername());
			}
		}
		if (task == null) {
			task = systemService.findUniqueByProperty(TSUser.class,"userName",ResourceUtil.getConfigByName("mini.user"));
			return org.jeecgframework.jwt.util.Result.error("获取用户信息失败");
		}
		if(!StringUtil.isEmpty(task.getDepartid())){
			TSDepart tsDepart = systemService.get(TSDepart.class,task.getDepartid());
			if(tsDepart!=null){
				tsDepart.setTSDeparts(null);
				tsDepart.setTSPDepart(null);
				task.setCurrentDepart(tsDepart);
			}else{
					try{
						TSUserOrg tsDepart1 =  task.getUserOrgList().get(0);

						tsDepart1.setTsDepart(null);
						task.setCurrentDepart (tsDepart1.getTsDepart());
					}catch (Exception e1){
					}

			}
		}
		task.setUserOrgList(null);

		try{
			if(StringUtil.isEmpty(task.getHomeUrl())){
				task.setHomeUrl("/home");
			}
		}catch (Exception e){

		}
		return org.jeecgframework.jwt.util.Result.success(task);
	}

	@RequestMapping(value = "/getno/{ordertype}", method = RequestMethod.GET)
	@ResponseBody
	@ApiOperation(value="根据ordertype获取no",notes="根据ordertype获取no",httpMethod="GET",produces="application/json")
	public ResponseMessage<?> getno(@ApiParam(required=false,name="ordertype",value="ordertype")@PathVariable("ordertype") String ordertype) {
		FxjProMainEntity fxjProMainEntity = systemService.findUniqueByProperty(FxjProMainEntity.class,"proNo",ordertype);

		String no = fxjUtil.getNextomNoticeId(ordertype);


		return org.jeecgframework.jwt.util.Result.success(no);
	}
	@RequestMapping(value = "/getfileno/{filetype}", method = RequestMethod.GET)
	@ResponseBody
	@ApiOperation(value="根据filetype获取no",notes="根据filetype获取no",httpMethod="GET",produces="application/json")
	public ResponseMessage<?> getfileno(@ApiParam(required=false,name="filetype",value="filetype")@PathVariable("filetype") String filetype) {
		String no = fxjUtil.getNextfileId(filetype);
		return org.jeecgframework.jwt.util.Result.success(no);
	}
	@RequestMapping(value = "/delfile/{fileId}", method = RequestMethod.GET)
	@ResponseBody
	@ApiOperation(value="根据id删除文件",notes="根据id删除文件",httpMethod="GET",produces="application/json")
	public ResponseMessage<?> delfile(@ApiParam(required=false,name="fileId",value="fileId")@PathVariable("fileId") String fileId) {
		 FxjOrderAttaEntity fxjOrderAttaEntity = systemService.get(FxjOrderAttaEntity.class,Integer.parseInt(fileId));
		fxjOrderAttaEntity.setBpmStatus("9");
		 systemService.updateEntitie(fxjOrderAttaEntity);
		 return org.jeecgframework.jwt.util.Result.success("ok");
	}

	@RequestMapping(value = "/delposfile/{fileId}", method = RequestMethod.GET)
	@ResponseBody
	@ApiOperation(value="根据id删除文件",notes="根据id删除文件",httpMethod="GET",produces="application/json")
	public ResponseMessage<?> delposfile(@ApiParam(required=false,name="fileId",value="fileId")@PathVariable("fileId") String fileId) {
		PosXjfjEntity posXjfjEntity = systemService.get(PosXjfjEntity.class,fileId);
		posXjfjEntity.setBpmStatus("9");
		systemService.updateEntitie(posXjfjEntity);
		return org.jeecgframework.jwt.util.Result.success("ok");
	}

	@RequestMapping(value = "/qrcode",method = RequestMethod.POST)
	@ResponseBody
	//update--begin--author:zhangjiaqiang date:20171030 for:增加swagger支持
	@ApiOperation(value="条码识别",notes="条码识别",httpMethod="POST",produces="application/json")
	//update--end--author:zhangjiaqiang date:20171030 for:增加swagger支持
	public String getqrcode(@ApiParam(required=true,name="imgfile",value="imgfile") @RequestParam("imgfile") String imgfile) {
		String qr_result="";
		BufferedImage image = null;
		try {
			if(StringUtil.isNotEmpty(imgfile)){
				if(imgfile.startsWith("http")){
					ImageIO.read( new URL(imgfile));
				}else{
					String savaPath= ResourceUtil.getConfigByName("webUploadpath");
					image = ImageIO.read(new File(savaPath+ File.separator+imgfile));
				}
			}
			LuminanceSource source = new BufferedImageLuminanceSource(image);
			Binarizer binarizer = new HybridBinarizer(source);
			BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);
			Map<DecodeHintType, Object> hints = new HashMap<DecodeHintType, Object>();
			hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
			Result result=new MultiFormatReader().decode(binaryBitmap,hints); // 对图像进行解码
   			qr_result= result.getText();//content.getString("zxing");
		} catch (IOException e) {
			e.printStackTrace();
		}catch (NotFoundException e) {
			e.printStackTrace();
		}

		return qr_result;
	}

	@RequestMapping(value="/uploadsb", method = RequestMethod.POST)
	@ApiOperation(value="图像识别",notes="图像识别",httpMethod="POST",produces="application/json")

	public @ResponseBody LinkedList<FileMeta> uploadsb(@RequestParam(value="filetype", required=false) String filetype,@RequestParam(value="sbtype", required=false) String sbtype,@RequestParam(value="orderNo", required=false) String orderNo,@RequestParam(value="cardid", required=false) String cardid,@RequestParam(value="realname", required=false) String realname,MultipartHttpServletRequest request, HttpServletResponse response) {
		com.zhaodui.jdwx.jdwxController jdwx = new jdwxController();
        LinkedList<FileMeta> files = new LinkedList<FileMeta>();
        FileMeta fileMeta = null;
		//1. build an iterator
		Iterator<String> itr =  request.getFileNames();
		MultipartFile mpf = null;
		String filest = orderNo;
		//2. get each file
		String savaPath= ResourceUtil.getConfigByName("webUploadpath");
		String filename="";
		String filenameweb="";

//     int filesize=files.size();
//     int  sizecount=0;

		String showAndDownUrl = ResourceUtil.getConfigByName("showAndDownUrl");
		String imgserver = ResourceUtil.getConfigByName("img.server");
		while(itr.hasNext()){
//            sizecount = sizecount + 1;
//            if(sizecount !=filesize ){
//                continue;
//            }
			//2.1 get next MultipartFile
			mpf = request.getFile(itr.next());
			System.out.println(mpf.getOriginalFilename() +" uploaded! "+files.size());

			//2.2 if files > 10 remove the first from the list
			if(files.size() >= 10){
				files.pop();
			}
			filename = filest + File.separator+mpf.getOriginalFilename();
			filenameweb = filest + "/"+mpf.getOriginalFilename();

			FxjOrderAttaEntity fxjOrderAttaEntity = new FxjOrderAttaEntity();
			fxjOrderAttaEntity.setOrderNo(orderNo);
            fxjOrderAttaEntity.setCreateDate(now());
			fxjOrderAttaEntity.setAttaName(filest+File.separator+mpf.getOriginalFilename());
			fxjOrderAttaEntity.setAttaSize(mpf.getSize()/1024 +" KB");
			fxjOrderAttaEntity.setAttaType(filetype);
			fxjOrderAttaEntity.setBpmStatus("1");
			fxjOrderAttaEntity.setAttaUrl(imgserver+showAndDownUrl+filenameweb);
			String fileId = systemService.save(fxjOrderAttaEntity).toString();
			//2.3 create new fileMeta
			fileMeta = new FileMeta();
			fileMeta.setFileId(fileId);
			fileMeta.setFileName(mpf.getOriginalFilename());
			fileMeta.setFileSize(mpf.getSize()/1024 +" KB");
			fileMeta.setFileType(mpf.getContentType());
			fileMeta.setFileUrl(fxjOrderAttaEntity.getAttaUrl());

			try {
				fileMeta.setBytes(mpf.getBytes());
				// copy file to local disk (make sure the path "e.g. D:/temp/files" exists)
				String ctxPath=savaPath;
              	File file = new File(ctxPath+ File.separator+filest);
				if (!file.exists()) {
					file.mkdirs();// 创建文件根目录
				}
				FileCopyUtils.copy(mpf.getBytes(), new FileOutputStream(ctxPath+File.separator+filename));
				System.out.println(" sbtype! "+sbtype);

			try{
				int angel = getRotateAngleForPhoto(ctxPath+File.separator+filename);
				System.out.println(">>>>>>>>>>>" + angel);
				if (angel > 0) {
					rotateImage(new File(ctxPath+File.separator+filename), angel);
				}
			}catch (Exception e){

			}

				String sbfilename = filename;
				Double fizesize = mpf.getSize()/1024.00/1024.00;
				if(fizesize > 1){   //如果大于2M则压缩
					int sizelimit = (int)Math.ceil(Math.sqrt(mpf.getSize()/1024.00/1024.00)/1);
					sbfilename = "suoluotu"+File.separator+filename;
					File filesl = new File(ctxPath+ File.separator+"suoluotu");
					if (!filesl.exists()) {
						filesl.mkdirs();// 创建文件根目录
					}
					Base64Utils.saveUrlAs(fxjOrderAttaEntity.getAttaUrl(),sbfilename,sizelimit);
				}
				if("6".equals(sbtype)){//行驶证识别
					fileMeta.setPiccontent(jdwx.dozjsb(sbfilename,sbtype,request));
				}if("99".equals(sbtype)){//人脸对比
					fileMeta.setPiccontent(jdwx.dorldb(cardid,realname,sbfilename,request));
				}if("yyzz".equals(sbtype)){//营业执照
					fileMeta.setPiccontent(jdwx.doyyzzsb(sbfilename,sbtype,request));
				}if("zzsfp".equals(sbtype)){//增值税发票
					fileMeta.setPiccontent(jdwx.dozzsfpsb(sbfilename,sbtype,request));
				}if("bdcz".equals(sbtype)){//不动产证
					fileMeta.setPiccontent(jdwx.doalbdcsb(sbfilename,sbtype,request));
				}else{//身份证识别
					fileMeta.setPiccontent(jdwx.dosfzsb(sbfilename,sbtype,request));
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			//2.4 add to files
			files.add(fileMeta);
		}
		// result will be like this
		// [{"fileName":"app_engine-85x77.png","fileSize":"8 Kb","fileType":"image/png"},...]

		return files;
	}



	@RequestMapping(value="/uploadzxsb", method = RequestMethod.POST)
	@ApiOperation(value="图像识别",notes="图像识别",httpMethod="POST",produces="application/json")

	public @ResponseBody LinkedList<FileMeta> uploadzxsb(@RequestParam(value="filetype", required=false) String filetype,@RequestParam(value="sbtype", required=false) String sbtype,@RequestParam(value="orderNo", required=false) String orderNo,@RequestParam(value="cardid", required=false) String cardid,@RequestParam(value="realname", required=false) String realname,MultipartHttpServletRequest request, HttpServletResponse response) {
		com.zhaodui.jdwx.jdwxController jdwx = new jdwxController();
		LinkedList<FileMeta> files = new LinkedList<FileMeta>();
		FileMeta fileMeta = null;
		//1. build an iterator
		Iterator<String> itr =  request.getFileNames();
		MultipartFile mpf = null;
		String filest = orderNo;
		//2. get each file
		String savaPath= ResourceUtil.getConfigByName("webUploadpath");
		String filename="";
		String filenameweb="";

//     int filesize=files.size();
//     int  sizecount=0;

		String showAndDownUrl = ResourceUtil.getConfigByName("showAndDownUrl");
		String imgserver = ResourceUtil.getConfigByName("img.server");
		while(itr.hasNext()){
//            sizecount = sizecount + 1;
//            if(sizecount !=filesize ){
//                continue;
//            }
			//2.1 get next MultipartFile
			mpf = request.getFile(itr.next());
			System.out.println(mpf.getOriginalFilename() +" uploaded! "+files.size());

			//2.2 if files > 10 remove the first from the list
			if(files.size() >= 10){
				files.pop();
			}
			filename = filest + File.separator+mpf.getOriginalFilename();
			filenameweb = filest + "/"+mpf.getOriginalFilename();

			FxjOrderAttaEntity fxjOrderAttaEntity = new FxjOrderAttaEntity();
			fxjOrderAttaEntity.setOrderNo(orderNo);
			fxjOrderAttaEntity.setCreateDate(now());
			fxjOrderAttaEntity.setAttaName(filest+File.separator+mpf.getOriginalFilename());
			fxjOrderAttaEntity.setAttaSize(mpf.getSize()/1024 +" KB");
			fxjOrderAttaEntity.setAttaType(filetype);
			fxjOrderAttaEntity.setBpmStatus("1");
			fxjOrderAttaEntity.setAttaUrl(imgserver+showAndDownUrl+filenameweb);
			String fileId = systemService.save(fxjOrderAttaEntity).toString();
			//2.3 create new fileMeta
			fileMeta = new FileMeta();
			fileMeta.setFileId(fileId);
			fileMeta.setFileName(mpf.getOriginalFilename());
			fileMeta.setFileSize(mpf.getSize()/1024 +" KB");
			fileMeta.setFileType(mpf.getContentType());
			fileMeta.setFileUrl(fxjOrderAttaEntity.getAttaUrl());

			try {
				fileMeta.setBytes(mpf.getBytes());
				// copy file to local disk (make sure the path "e.g. D:/temp/files" exists)
				String ctxPath=savaPath;
				File file = new File(ctxPath+ File.separator+filest);
				if (!file.exists()) {
					file.mkdirs();// 创建文件根目录
				}
				FileCopyUtils.copy(mpf.getBytes(), new FileOutputStream(ctxPath+File.separator+filename));
				System.out.println(" sbtype! "+sbtype);



				String sbfilename = filename;
				Double fizesize = mpf.getSize()/1024.00/1024.00;
//				if(fizesize > 1){   //如果大于2M则压缩
//					int sizelimit = (int)Math.ceil(Math.sqrt(mpf.getSize()/1024.00/1024.00)/1);
//					sbfilename = "suoluotu"+File.separator+filename;
//					File filesl = new File(ctxPath+ File.separator+"suoluotu");
//					if (!filesl.exists()) {
//						filesl.mkdirs();// 创建文件根目录
//					}
//					Base64Utils.saveUrlAs(fxjOrderAttaEntity.getAttaUrl(),sbfilename,sizelimit);
//				}
				// 初始化一个AipOcr
				AipOcr client = new AipOcr(APP_ID, API_KEY, SECRET_KEY);

				// 可选：设置网络连接参数
				client.setConnectionTimeoutInMillis(2000);
				client.setSocketTimeoutInMillis(60000);
//				fileMeta.setPiccontent(jdwx.dosfzsb(sbfilename,sbtype,request));
//				String path = "c://a.jpg";
				JSONObject res = client.basicGeneral(sbfilename, new HashMap<String, String>());
				fileMeta.setPiccontent(res.toString(2));
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			//2.4 add to files
			files.add(fileMeta);
		}
		// result will be like this
		// [{"fileName":"app_engine-85x77.png","fileSize":"8 Kb","fileType":"image/png"},...]

		return files;
	}

	@RequestMapping(value="/posupload", method = RequestMethod.POST)
	@ApiOperation(value="POS附件上传",notes="POS附件上传",httpMethod="POST",produces="application/json")
	public @ResponseBody LinkedList<FileMeta> posupload(@RequestParam(value="fileName", required=false) String fileName,@RequestParam(value="posXjid", required=false) String posXjid,MultipartHttpServletRequest request, HttpServletResponse response) {
		LinkedList<FileMeta> files = new LinkedList<FileMeta>();
		String showAndDownUrl = ResourceUtil.getConfigByName("showAndDownUrl");
		String imgserver = ResourceUtil.getConfigByName("img.server");
		FileMeta fileMeta = null;
		//1. build an iterator
		Iterator<String> itr =  request.getFileNames();
		MultipartFile mpf = null;
		String filest = posXjid;
		//2. get each file
		String savaPath= ResourceUtil.getConfigByName("webUploadpath");
		String  filename = "";
		String  filenameweb = "";
		while(itr.hasNext()){

			//2.1 get next MultipartFile
			mpf = request.getFile(itr.next());
			System.out.println(mpf.getOriginalFilename() +" uploaded! "+files.size());

			//2.2 if files > 10 remove the first from the list

			filename = filest + File.separator+mpf.getOriginalFilename();
			filenameweb = filest + "/"+mpf.getOriginalFilename();

			PosXjfjEntity posXjfjEntity = new PosXjfjEntity();
			posXjfjEntity.setPosXjid(posXjid);
			posXjfjEntity.setPosXjfjname(fileName);
			posXjfjEntity.setCreateDate(now());

			posXjfjEntity.setPosXjfjurl(imgserver+showAndDownUrl+filenameweb);
			String fileId = systemService.save(posXjfjEntity).toString();
			//2.3 create new fileMeta
			fileMeta = new FileMeta();
			fileMeta.setFileId(fileId);
			fileMeta.setFileName(mpf.getOriginalFilename());
			fileMeta.setFileSize(mpf.getSize()/1024+" KB");
			fileMeta.setFileType(mpf.getContentType());
			fileMeta.setFileUrl(posXjfjEntity.getPosXjfjurl());
			try {
				fileMeta.setBytes(mpf.getBytes());
				// copy file to local disk (make sure the path "e.g. D:/temp/files" exists)
				String ctxPath=savaPath;

				File file = new File(ctxPath+File.separator+filest);
				if (!file.exists()) {
					file.mkdirs();// 创建文件根目录
				}
				FileCopyUtils.copy(mpf.getBytes(), new FileOutputStream(ctxPath+File.separator+filename));

//               try{
//				   AliyunOSSClientUtil t = new AliyunOSSClientUtil();
//				   System.out.println("ctxPath+File.separator+filename"+ctxPath+File.separator+filename);
//				   String url = t.uploadvideo(ctxPath+File.separator+filename);
//				   PosXjfjEntity posXjfjEntitynew =  systemService.get(PosXjfjEntity.class,fileId);
//				   posXjfjEntitynew.setPosXjfjurl("https://zhaodui.oss-cn-shenzhen.aliyuncs.com/"+url);
//				   systemService.updateEntitie(posXjfjEntitynew);
//				   fileMeta.setFileUrl(posXjfjEntitynew.getPosXjfjurl());
//
//			   }catch (Exception ue){
//
//				}

//				try{
//					int angel = getRotateAngleForPhoto(ctxPath+File.separator+filename);
//					System.out.println(">>>>>>>>>>>" + angel);
//					if (angel > 0) {
//						rotateImage(new File(ctxPath+File.separator+filename), angel);
//					}
//				}catch (Exception e){
//
//				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			//2.4 add to files
			files.add(fileMeta);
		}
		// result will be like this
		// [{"fileName":"app_engine-85x77.png","fileSize":"8 Kb","fileType":"image/png"},...]
		return files;
	}
	@RequestMapping(value="/getzipfile", method = RequestMethod.GET)
	@ApiOperation(value="根据fileName压缩文件并获取",notes="根据fileName压缩文件并获取",httpMethod="GET",produces="application/json")
	public @ResponseBody LinkedList<FileMeta> zipfile(@RequestParam(value="fileName", required=false) String fileName, HttpServletResponse response) {
		LinkedList<FileMeta> files = new LinkedList<FileMeta>();
		String showAndDownUrl = ResourceUtil.getConfigByName("showAndDownUrl");
		String imgserver = ResourceUtil.getConfigByName("img.server");
		FileMeta fileMeta = null;
		String filest = fileName+".zip";
		String savaPath= ResourceUtil.getConfigByName("webUploadpath");
		try {
				String ctxPath=savaPath;
				File file = new File(ctxPath+File.separator+filest);
				if (file.exists()) {
					file.delete();// 删除ZIP文件
				}
				ZipUtil.compress(ctxPath+File.separator+fileName,ctxPath+File.separator+filest);
				} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
		}
			fileMeta = new FileMeta();
			fileMeta.setFileUrl(imgserver+showAndDownUrl+filest+"?down=true");
			files.add(fileMeta);
		return files;
	}

	@RequestMapping(value="/upload", method = RequestMethod.POST)
	@ApiOperation(value="图片上传",notes="图片上传",httpMethod="POST",produces="application/json")
	public @ResponseBody LinkedList<FileMeta> upload(@RequestParam(value="filetype", required=false) String filetype,@RequestParam(value="orderNo", required=false) String orderNo,MultipartHttpServletRequest request, HttpServletResponse response) {
        LinkedList<FileMeta> files = new LinkedList<FileMeta>();
		String showAndDownUrl = ResourceUtil.getConfigByName("showAndDownUrl");
		String imgserver = ResourceUtil.getConfigByName("img.server");
        FileMeta fileMeta = null;
		//1. build an iterator
		Iterator<String> itr =  request.getFileNames();
		MultipartFile mpf = null;
        String filest = orderNo;
		//2. get each file
		String savaPath= ResourceUtil.getConfigByName("webUploadpath");
       String  filename = "";
		String  filenameweb = "";
		while(itr.hasNext()){

			//2.1 get next MultipartFile
			mpf = request.getFile(itr.next());
			System.out.println(mpf.getOriginalFilename() +" uploaded! "+files.size());

			//2.2 if files > 10 remove the first from the list

			filename = filest + File.separator+mpf.getOriginalFilename();
			filenameweb = filest + "/"+mpf.getOriginalFilename();

			FxjOrderAttaEntity fxjOrderAttaEntity = new FxjOrderAttaEntity();
			fxjOrderAttaEntity.setOrderNo(orderNo);
            fxjOrderAttaEntity.setCreateDate(now());
			fxjOrderAttaEntity.setAttaName(filest+File.separator+mpf.getOriginalFilename());
			fxjOrderAttaEntity.setAttaSize(mpf.getSize()/1024+" KB");
			fxjOrderAttaEntity.setBpmStatus("1");
			fxjOrderAttaEntity.setAttaType(filetype);
			fxjOrderAttaEntity.setAttaUrl(imgserver+showAndDownUrl+filenameweb);
			String fileId = systemService.save(fxjOrderAttaEntity).toString();
			//2.3 create new fileMeta
			fileMeta = new FileMeta();
			fileMeta.setFileId(fileId);
			fileMeta.setFileName(mpf.getOriginalFilename());
			fileMeta.setFileSize(mpf.getSize()/1024+" KB");
			fileMeta.setFileType(mpf.getContentType());
			fileMeta.setFileUrl(fxjOrderAttaEntity.getAttaUrl());
			try {
				fileMeta.setBytes(mpf.getBytes());
				// copy file to local disk (make sure the path "e.g. D:/temp/files" exists)
				String ctxPath=savaPath;

				File file = new File(ctxPath+File.separator+filest);
				if (!file.exists()) {
					file.mkdirs();// 创建文件根目录
				}
				FileCopyUtils.copy(mpf.getBytes(), new FileOutputStream(ctxPath+File.separator+filename));
				try{
					int angel = getRotateAngleForPhoto(ctxPath+File.separator+filename);
					System.out.println(">>>>>>>>>>>" + angel);
					if (angel > 0) {
						rotateImage(new File(ctxPath+File.separator+filename), angel);
					}
				}catch (Exception e){

				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			//2.4 add to files
			files.add(fileMeta);
		}
		// result will be like this
		// [{"fileName":"app_engine-85x77.png","fileSize":"8 Kb","fileType":"image/png"},...]
		return files;
	}

	@RequestMapping(value="/uploadfile", method = RequestMethod.POST)
	public @ResponseBody LinkedList<FileMeta> uploadfile(@RequestParam(value="filetype", required=false) String filetype,@RequestParam(value="fileNo", required=false) String fileNo,MultipartHttpServletRequest request, HttpServletResponse response) {
		LinkedList<FileMeta> files = new LinkedList<FileMeta>();
		String showAndDownUrl = ResourceUtil.getConfigByName("showAndDownUrl");
		String imgserver = ResourceUtil.getConfigByName("img.server");
		FileMeta fileMeta = null;
		//1. build an iterator
		Iterator<String> itr =  request.getFileNames();
		MultipartFile mpf = null;
		String filest = DateUtils.date2Str(DateUtils.yyyymmddhhmmss);
		//2. get each file
		String savaPath= ResourceUtil.getConfigByName("webUploadpath");
		String  filename = "";
		while(itr.hasNext()){

			//2.1 get next MultipartFile
			mpf = request.getFile(itr.next());
			System.out.println(mpf.getOriginalFilename() +" uploaded! "+files.size());

			//2.2 if files > 10 remove the first from the list

			filename = filest + File.separator+mpf.getOriginalFilename();
			FxjFileListEntity fxjFileListEntity = new FxjFileListEntity();
			fxjFileListEntity.setFileNo(fileNo);
			fxjFileListEntity.setCreateDate(now());
			fxjFileListEntity.setFileName(filest+File.separator+mpf.getOriginalFilename());
			fxjFileListEntity.setFileSize(mpf.getSize()/1024+" KB");
			fxjFileListEntity.setFileType(filetype);
			if(filename.indexOf("png") != -1||filename.indexOf("jpg") != -1||filename.indexOf("jpeg") != -1){
                fxjFileListEntity.setFileUrl(imgserver+showAndDownUrl+filename);
            }else{
                fxjFileListEntity.setFileUrl(imgserver+showAndDownUrl+filename+"?down=true");
            }

			systemService.save(fxjFileListEntity);
			//2.3 create new fileMeta
			fileMeta = new FileMeta();
			fileMeta.setFileName(mpf.getOriginalFilename());
			fileMeta.setFileSize(mpf.getSize()/1024 +" KB");
			fileMeta.setFileType(mpf.getContentType());
			try {
				fileMeta.setBytes(mpf.getBytes());
				// copy file to local disk (make sure the path "e.g. D:/temp/files" exists)
				String ctxPath=savaPath;

				File file = new File(ctxPath+File.separator+filest);
				if (!file.exists()) {
					file.mkdirs();// 创建文件根目录
				}
				FileCopyUtils.copy(mpf.getBytes(), new FileOutputStream(ctxPath+File.separator+filename));
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			//2.4 add to files
			files.add(fileMeta);
		}
		// result will be like this
		// [{"fileName":"app_engine-85x77.png","fileSize":"8 Kb","fileType":"image/png"},...]
		return files;
	}

//	/***************************************************
//	 * URL: /rest/controller/get/{value}
//	 * get(): get file as an attachment
//	 * @param response : passed by the server
//	 * @param value : value from the URL
//	 * @return void
//	 ****************************************************/
//	@RequestMapping(value = "/get/{value}", method = RequestMethod.GET)
//	public void get(HttpServletResponse response,@PathVariable String value){
//		FileMeta getFile = files.get(Integer.parseInt(value));
//		try {
//			response.setContentType(getFile.getFileType());
//			response.setHeader("Content-disposition", "attachment; filename=\""+getFile.getFileName()+"\"");
//			FileCopyUtils.copy(getFile.getBytes(), response.getOutputStream());
//		}catch (IOException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
//	}
	/**
	 * 获取图片流/获取文件用于下载
	 * @param response
	 * @param request
	 * @throws Exception
	 * http://localhost:8080/zzwms/myBaseController/showOrDownqrcodeByurl.do?&qrvalue=1111223333  调用
	 */
	@RequestMapping(value="showOrDownqrcodeByurl",method = RequestMethod.GET)
	public void getQrImgByurl(HttpServletResponse response, HttpServletRequest request) throws Exception{
		request.setCharacterEncoding("UTF-8");
		String flag=request.getParameter("down");//是否下载否则展示图片

		String qrvalue = request.getParameter("qrvalue");
		String dbpath = qrvalue+".jpg";
		String localPath=ResourceUtil.getConfigByName("webUploadpath");

		try{
			String imgurl = localPath+File.separator+dbpath;
			QRcodeUtil.encode(qrvalue,imgurl);
		}catch (Exception e){

		}
		if("1".equals(flag)){
			response.setContentType("application/x-msdownload;charset=utf-8");
			String fileName=dbpath.substring(dbpath.lastIndexOf(File.separator)+1);

			String userAgent = request.getHeader("user-agent").toLowerCase();
			if (userAgent.contains("msie") || userAgent.contains("like gecko") ) {
				fileName = URLEncoder.encode(fileName, "UTF-8");
			}else {
				fileName = new String(fileName.getBytes("UTF-8"), "iso-8859-1");
			}
			response.setHeader("Content-disposition", "attachment; filename="+ fileName);

		}else{
			response.setContentType("image/jpeg;charset=utf-8");
		}

		InputStream inputStream = null;
		OutputStream outputStream=null;
		try {
			String imgurl = localPath+File.separator+dbpath;
			inputStream = new BufferedInputStream(new FileInputStream(imgurl));
			outputStream = response.getOutputStream();
			byte[] buf = new byte[1024];
			int len;
			while ((len = inputStream.read(buf)) > 0) {
				outputStream.write(buf, 0, len);
			}
			response.flushBuffer();
		} catch (Exception e) {

		}finally{
			if(inputStream!=null){
				inputStream.close();
			}
			if(outputStream!=null){
				outputStream.close();
			}
		}
	}

    @RequestMapping(value = "/print/{username}", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value="打印",notes="打印",httpMethod="GET",produces="application/json")
    public ResponseMessage<?> printfile(@ApiParam(required=false,name="username",value="username")@PathVariable("username") String username) {
        String no = fxjUtil.getNextomNoticeId("");

        OutputStream fileOut = null;
        BufferedImage bufferImg = null;
        String codedFileName = null;
        try {
            HSSFWorkbook wb = new HSSFWorkbook();
            HSSFSheet sheet = wb.createSheet("出货通知");
            sheet.setColumnWidth(0, 5 * 256);
            sheet.setColumnWidth(1, 10 * 256);
            sheet.setColumnWidth(2, 10 * 200);
            sheet.setColumnWidth(3, 8 * 256);
            sheet.setColumnWidth(4, 8 * 256);
            sheet.setColumnWidth(5, 8 * 256);
            sheet.setColumnWidth(6, 8 * 256);
            sheet.setColumnWidth(7, 8 * 256);
            sheet.setColumnWidth(8, 25 * 256);
            // 创建第一行
            Row row = sheet.createRow((short) 0);   //第一行空白
            // 创建两种单元格格式
            CellStyle cs = wb.createCellStyle();
            CellStyle cs2 = wb.createCellStyle();
            CellStyle cs3 = wb.createCellStyle();
            CellStyle cs4 = wb.createCellStyle();
            // 创建两种字体
            Font f = wb.createFont();
            Font f2 = wb.createFont();
            // 创建第一种字体样式（用于列名）
            f.setFontHeightInPoints((short) 16);
            f.setColor(IndexedColors.BLACK.getIndex());
            f.setBoldweight(Font.BOLDWEIGHT_BOLD);
            // 创建第二种字体样式（用于值）
            f2.setFontHeightInPoints((short) 10);
            f2.setColor(IndexedColors.BLACK.getIndex());
//	        Font f3=wb.createFont();
//	        f3.setFontHeightInPoints((short) 10);
//	        f3.setColor(IndexedColors.RED.getIndex());
            // 设置第一种单元格的样式（用于列名）
            cs.setFont(f);
            cs.setBorderLeft(CellStyle.BORDER_NONE);
            cs.setBorderRight(CellStyle.BORDER_NONE);
            cs.setBorderTop(CellStyle.BORDER_NONE);
            cs.setBorderBottom(CellStyle.BORDER_NONE);
            cs.setAlignment(HSSFCellStyle.ALIGN_CENTER);
            // 设置第二种单元格的样式（用于值）
            cs2.setFont(f2);
            cs2.setBorderLeft(CellStyle.BORDER_NONE);
            cs2.setBorderRight(CellStyle.BORDER_NONE);
            cs2.setBorderTop(CellStyle.BORDER_NONE);
            cs2.setBorderBottom(CellStyle.BORDER_NONE);
            cs2.setWrapText(true);
//	        cs2.setAlignment(CellStyle.BODER_NONE);
            cs3.setFont(f2);
            cs3.setBorderLeft(CellStyle.BORDER_MEDIUM);
            cs3.setBorderRight(CellStyle.BORDER_MEDIUM);
            cs3.setBorderTop(CellStyle.BORDER_MEDIUM);
            cs3.setBorderBottom(CellStyle.BORDER_MEDIUM);
//	        cs3.setAlignment(CellStyle.BORDER_HAIR);
            cs4.setFont(f2);
            cs4.setBorderTop(CellStyle.BORDER_MEDIUM);
            cs4.setBorderBottom(CellStyle.BORDER_MEDIUM);
            Row row1 = sheet.createRow((short) 1);   //第二行标题
            row1.setHeight((short)700);
            Cell cellTitle = row1.createCell(0);
            cellTitle.setCellValue(username+"出货通知");
            cellTitle.setCellStyle(cs);
            Row rowHead1=sheet.createRow((short) 2);  //头部第一行
            Cell cellHead11 = rowHead1.createCell(0);
            cellHead11.setCellValue("通知单号：");
            cellHead11.setCellStyle(cs2);
            // 第七步，将文件存到指定位置
            String filename = "E:/"+username+".xls";
            try {
                FileOutputStream fileOutputStream = new FileOutputStream(filename);//指定路径与名字和格式
                wb.write(fileOutputStream);//将数据写出去
                fileOutputStream.close();//关闭输出流
                printUtil.printfile(filename);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            if(fileOut != null){
                try {
                    fileOut.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return org.jeecgframework.jwt.util.Result.success(no);
    }
	@RequestMapping(value = "/getcon/{orderNo}", method = RequestMethod.POST,consumes = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	//update--begin--author:zhangjiaqiang date:20171030 for:增加swagger支持
	@ApiOperation(value="根据orderNo查找合同",notes="orderNo",httpMethod="POST",produces="application/json")
	//update--end--author:zhangjiaqiang date:20171030 for:增加swagger支持
	public ResponseMessage<conHead> getcon(@ApiParam(required=true,name="orderNo",value="orderNo")@PathVariable("orderNo") String orderNo, @RequestBody conHead conHead) {

		try {

			Map<String, Object> data = new HashMap<String, Object>();

			for(conmap t:conHead.getConmapList()){
				data.put(t.getConKey(), t.getConValue());
			}
			long time1 = System.currentTimeMillis();
			Java2word j2w = new Java2word();
			String showAndDownUrl = ResourceUtil.getConfigByName("showAndDownUrl");
			String imgserver = ResourceUtil.getConfigByName("img.server");
			String filest = DateUtils.date2Str(DateUtils.yyyymmddhhmmss);
			String savaPath= ResourceUtil.getConfigByName("webUploadpath");
           String fileurl = orderNo+  "/"  +filest+  "/" +orderNo+".doc";
			savaPath = savaPath + "/" + orderNo+  "/"  +filest;
			String fileName = orderNo;

			conHead.setContoUrl(imgserver+showAndDownUrl+fileurl+"?down=true");
			j2w.toWord(conHead.getContempPath(), savaPath, fileName, data);
			long time2 = System.currentTimeMillis();
			System.out.println("Java2word cost time : " + (time2 - time1));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return org.jeecgframework.jwt.util.Result.success(conHead);

	}
	}
